<template>
  <div class="main-app">
    <!-- 顶部导航栏 -->
    <header class="app-header">
      <div class="header-content">
        <div class="logo-section">
          <el-icon size="40" color="#409eff"><ChatDotRound /></el-icon>
          <h1>AI智能学习助手</h1>
        </div>

        <div class="user-section">
          <el-dropdown @command="handleUserCommand">
            <div class="user-info">
              <el-avatar :size="36" :src="userInfo?.avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span>{{ userInfo?.username || '用户' }}</span>
              <el-icon><ArrowDown /></el-icon>
            </div>

            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <main class="app-main">
      <div class="main-container">
        <el-row :gutter="24" class="main-row">
          <!-- 侧边栏切换按钮 -->
          <div class="sidebar-toggle" @click="toggleSidebar">
            <el-icon :size="20">
              <component :is="sidebarCollapsed ? 'Expand' : 'Fold'" />
            </el-icon>
          </div>

          <!-- 左侧功能区 -->
          <el-col :span="sidebarCollapsed ? 0 : (isTabletLandscape ? 5 : 6)" class="sidebar-col">
            <div class="function-panel" :class="{ 'collapsed': sidebarCollapsed }">
              <!-- 功能选择卡片 -->
              <el-card class="function-card">
                <template #header>
                  <div class="card-header">
                    <el-icon size="24"><Menu /></el-icon>
                    <span>功能选择</span>
                  </div>
                </template>

                <div class="function-buttons">
                  <el-button
                    :type="activeFunction === 'search' ? 'primary' : 'default'"
                    size="large"
                    @click="() => setActiveFunction('search')"
                    class="function-btn"
                  >
                    <el-icon><Search /></el-icon>
                    拍照搜题
                  </el-button>

                  <el-button
                    :type="activeFunction === 'chat' ? 'primary' : 'default'"
                    size="large"
                    @click="() => setActiveFunction('chat')"
                    class="function-btn"
                  >
                    <el-icon><ChatDotRound /></el-icon>
                    AI对话
                  </el-button>

                  <el-button
                    :type="activeFunction === 'ocr' ? 'primary' : 'default'"
                    size="large"
                    @click="() => setActiveFunction('ocr')"
                    class="function-btn"
                  >
                    <el-icon><Document /></el-icon>
                    OCR识别
                  </el-button>
                </div>
              </el-card>

              <!-- 会话管理 -->
              <el-card class="session-card" v-if="activeFunction === 'chat'">
                <template #header>
                  <div class="card-header">
                    <el-icon size="24"><ChatDotRound /></el-icon>
                    <span>会话管理</span>
                    <el-button type="primary" size="small" @click="createNewSession">
                      <el-icon><Plus /></el-icon>
                      新建会话
                    </el-button>
                  </div>
                </template>

                <div class="session-list">
                  <div
                    v-for="(session, index) in sessions"
                    :key="session.id"
                    :class="['session-item', {
                      active: currentSessionId === session.id,
                      hidden: index >= maxVisibleSessions
                    }]"
                    @click="switchSession(session.id)"
                  >
                    <div class="session-info">
                      <div class="session-title">{{ session.title }}</div>
                      <div class="session-time">{{ formatTime(session.updateTime) }}</div>
                    </div>
                    <el-button
                      type="text"
                      size="small"
                      @click.stop="handleDeleteSession(session.id)"
                      class="delete-btn"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
              </el-card>
            </div>
          </el-col>

          <!-- 右侧内容区 -->
          <el-col :span="sidebarCollapsed ? 24 : (isTabletLandscape ? 19 : 18)" class="content-col">
            <div class="content-panel">
              <!-- 拍照搜题功能 -->
              <SearchFunction
                v-if="activeFunction === 'search'"
                @search-result="handleSearchResult"
              />

              <!-- AI对话功能 -->
              <ChatFunction
                v-if="activeFunction === 'chat'"
                :session-id="currentSessionId"
                @message-sent="handleMessageSent"
              />

              <!-- OCR识别功能 -->
              <OcrFunction
                v-if="activeFunction === 'ocr'"
                @ocr-result="handleOcrResult"
                @send-to-chat="handleOcrToChat"
              />
            </div>
          </el-col>
        </el-row>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ChatDotRound, User, ArrowDown, Menu, Search, Document, Plus, Delete, Expand, Fold
} from '@element-plus/icons-vue'
import { getUserInfo, clearAuth } from '@/utils/auth'
import { createSession as apiCreateSession, deleteSession as apiDeleteSession, getUserSessions } from '@/api/tutor'
import SearchFunction from '@/components/SearchFunction.vue'
import ChatFunction from '@/components/ChatFunction.vue'
import OcrFunction from '@/components/OcrFunction.vue'

const router = useRouter()

// 用户信息
const userInfo = computed(() => getUserInfo())

// 当前激活的功能
const activeFunction = ref('search')

// 侧边栏状态
const sidebarCollapsed = ref(false)

// 会话显示限制
const maxVisibleSessions = ref(8)

// 响应式检测
const isTabletLandscape = ref(false)

// 会话管理
const sessions = ref([])
const currentSessionId = ref(null)

// 设置激活功能
const setActiveFunction = async (func) => {
  console.log('🎯 切换功能:', func)
  activeFunction.value = func

  if (func === 'chat') {
    console.log('💬 切换到聊天功能，检查会话状态')
    console.log('📋 当前会话列表数量:', sessions.value.length)
    console.log('🎯 当前会话ID:', currentSessionId.value)

    // 确保有有效的会话
    if (sessions.value.length === 0 || !currentSessionId.value) {
      console.log('📝 没有有效会话，创建新会话')
      await createNewSession()
    } else {
      console.log('✅ 已有有效会话，会话ID:', currentSessionId.value)
    }
  }
}

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 检测屏幕尺寸
const checkScreenSize = () => {
  const width = window.innerWidth
  const height = window.innerHeight

  // 平板横屏检测 (宽度 > 768px 且 宽度 > 高度)
  isTabletLandscape.value = width > 768 && width > height && width <= 1200

  // 在小屏幕上自动收起侧边栏
  if (width <= 768) {
    sidebarCollapsed.value = true
  }
}

// 创建新会话
const createNewSession = async () => {
  const userId = userInfo.value?.id
  console.log('➕ 开始创建新会话，用户ID:', userId)

  if (!userId) {
    console.log('❌ 用户未登录，无法创建会话')
    ElMessage.error('请先登录')
    return
  }

  try {
    const sessionData = {
      userId: userId,
      title: `会话 ${sessions.value.length + 1}`
    }
    console.log('📡 调用createSession API，数据:', sessionData)

    const response = await apiCreateSession(sessionData)
    console.log('📄 createSession API响应:', response)

    if (response.success || response.code === 200) {
      const newSession = response.data.session
      console.log('✅ 会话创建成功:', newSession)

      sessions.value.unshift(newSession)
      currentSessionId.value = newSession.id
      console.log('📋 更新会话列表，当前会话ID:', currentSessionId.value)

      ElMessage.success('新会话已创建')
    } else {
      console.error('❌ 创建会话失败:', response.message)
      ElMessage.error(response.message || '创建会话失败')
    }
  } catch (error) {
    console.error('❌ 创建会话异常:', error)
    ElMessage.error('创建会话失败，请重试')
  }
}

// 切换会话
const switchSession = (sessionId) => {
  currentSessionId.value = sessionId
}

// 处理删除会话
const handleDeleteSession = async (sessionId) => {
  const userId = userInfo.value?.id
  if (!userId) {
    ElMessage.error('请先登录')
    return
  }

  try {
    await ElMessageBox.confirm('确定要删除这个会话吗？删除后无法恢复。', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await apiDeleteSession({
      userId: userId,
      sessionId: sessionId
    })

    if (response.success || response.code === 200) {
      const index = sessions.value.findIndex(s => s.id === sessionId)
      if (index > -1) {
        sessions.value.splice(index, 1)

        // 如果删除的是当前会话，切换到第一个会话
        if (currentSessionId.value === sessionId) {
          currentSessionId.value = sessions.value.length > 0 ? sessions.value[0].id : null
        }
      }

      ElMessage.success('会话已删除')
    } else {
      ElMessage.error(response.message || '删除会话失败')
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('删除会话失败:', error)
      ElMessage.error('删除会话失败，请重试')
    }
  }
}

// 处理用户下拉菜单
const handleUserCommand = (command) => {
  if (command === 'logout') {
    clearAuth()
    ElMessage.success('已退出登录')
    router.push('/login')
  }
}

// 处理搜题结果
const handleSearchResult = (result) => {
  console.log('搜题结果:', result)
}

// 处理消息发送
const handleMessageSent = (message) => {
  // 更新会话的最后更新时间（Redis会自动更新）
  const session = sessions.value.find(s => s.id === currentSessionId.value)
  if (session) {
    session.updateTime = new Date()
  }
}

// 处理OCR结果
const handleOcrResult = (result) => {
  console.log('OCR结果:', result)
}

// 处理OCR发送到聊天
const handleOcrToChat = (data) => {
  // 切换到聊天功能
  setActiveFunction('chat')

  // 如果没有当前会话，创建新会话
  if (!currentSessionId.value) {
    createNewSession()
  }

  // 将OCR结果发送到聊天
  // 这里可以通过事件总线或者其他方式传递数据到ChatFunction组件
  ElMessage.success('OCR结果已发送到AI对话')
}

// 加载会话从Redis
const loadSessions = async () => {
  const userId = userInfo.value?.id
  console.log('🔄 开始加载会话，用户ID:', userId)

  if (!userId) {
    console.log('⚠️ 用户未登录，跳过加载会话')
    return
  }

  try {
    console.log('📡 调用getUserSessions API，用户ID:', userId, '限制数量:', maxVisibleSessions.value)
    const response = await getUserSessions(userId, maxVisibleSessions.value)
    console.log('📄 getUserSessions API响应:', response)

    if (response.success || response.code === 200) {
      const data = response.data
      console.log('✅ API调用成功，会话数据:', data)

      sessions.value = data.sessions || []
      console.log('📋 设置会话列表，数量:', sessions.value.length)

      if (sessions.value.length > 0) {
        currentSessionId.value = sessions.value[0].id
        console.log('🎯 设置当前会话ID:', currentSessionId.value)
      } else {
        console.log('📝 没有会话，创建默认会话')
        // 如果没有会话，创建一个默认会话
        await createNewSession()
      }
    } else {
      console.error('❌ 加载会话失败:', response.message)
      console.error('❌ 完整响应:', response)
      // 创建一个默认会话
      await createNewSession()
    }
  } catch (error) {
    console.error('❌ 加载会话异常:', error)
    // 创建一个默认会话
    await createNewSession()
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date

  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  return date.toLocaleDateString()
}

// 验证和刷新用户信息
const validateUserInfo = () => {
  const currentUserInfo = getUserInfo()
  console.log('🔍 当前用户信息:', currentUserInfo)

  if (!currentUserInfo) {
    console.warn('⚠️ 没有找到用户信息，可能需要重新登录')
    return
  }

  // 检查用户ID
  const userId = currentUserInfo.id || currentUserInfo.userId
  if (!userId) {
    console.warn('⚠️ 用户信息缺少ID字段')
    console.log('📋 完整用户信息:', currentUserInfo)
  } else {
    console.log('✅ 用户ID:', userId)
  }

  // 检查用户名
  if (!currentUserInfo.username || currentUserInfo.username === '用户') {
    console.warn('⚠️ 用户信息缺少有效的用户名')
  } else {
    console.log('✅ 用户名:', currentUserInfo.username)
  }

  // 显示完整的用户信息用于调试
  console.log('📊 用户信息详情:', {
    id: currentUserInfo.id,
    userId: currentUserInfo.userId,
    username: currentUserInfo.username,
    nickname: currentUserInfo.nickname,
    email: currentUserInfo.email,
    phone: currentUserInfo.phone,
    loginTime: currentUserInfo.loginTime,
    loginType: currentUserInfo.loginType
  })
}

// 初始化
onMounted(async () => {
  validateUserInfo()
  await loadSessions()

  // 初始化屏幕尺寸检测
  checkScreenSize()
  window.addEventListener('resize', checkScreenSize)
})

// 清理事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', checkScreenSize)
})

// 监听用户信息变化，重新加载会话
watch(() => userInfo.value?.id, async (newUserId, oldUserId) => {
  if (newUserId && newUserId !== oldUserId) {
    // 用户切换时，重新加载该用户的会话
    sessions.value = []
    currentSessionId.value = null
    await loadSessions()
  }
}, { immediate: false })
</script>

<style scoped>
.main-app {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  display: flex;
  flex-direction: column;
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
}

.main-app::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 119, 198, 0.1) 0%, transparent 50%);
  pointer-events: none;
  z-index: 0;
}

/* 顶部导航栏 */
.app-header {
  width: 100%;
  height: 70px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.08);
  flex-shrink: 0;
  z-index: 100;
  position: fixed;
  top: 0;
  left: 0;
}

.app-header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(59, 130, 246, 0.3), transparent);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  width: 100%;
  height: 70px;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 16px;
  position: relative;
}

.logo-section .el-icon {
  color: #3b82f6;
  font-size: 36px;
  filter: drop-shadow(0 2px 4px rgba(59, 130, 246, 0.3));
  transition: all 0.3s ease;
}

.logo-section .el-icon:hover {
  transform: scale(1.05);
  filter: drop-shadow(0 4px 8px rgba(59, 130, 246, 0.4));
}

.logo-section h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  padding: 12px 16px;
  border-radius: 16px;
  transition: all 0.3s ease;
  font-size: 15px;
  color: #475569;
  background: rgba(255, 255, 255, 0.6);
  border: 1px solid rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(10px);
}

.user-info:hover {
  background: rgba(59, 130, 246, 0.1);
  color: #3b82f6;
  border-color: rgba(59, 130, 246, 0.2);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
}

/* 主要内容区域 */
.app-main {
  width: 100%;
  height: calc(100vh - 70px);
  padding: 16px 24px;
  position: fixed;
  top: 70px;
  left: 0;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  overflow: hidden;
}

/* 侧边栏切换按钮 */
.sidebar-toggle {
  position: absolute;
  top: 20px;
  left: -12px;
  z-index: 1000;
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  color: white;
}

.sidebar-toggle:hover {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
  transform: scale(1.1) rotate(180deg);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

.main-row {
  position: relative;
  width: 100%;
  height: 100%;
  transition: all 0.3s ease;
}

.main-container {
  width: 100%;
  height: 100%;
  position: relative;
}

/* 侧边栏列 */
.sidebar-col {
  height: 100%;
  transition: all 0.3s ease;
  overflow: hidden;
}

.sidebar-col.el-col-0 {
  width: 0 !important;
  padding: 0 !important;
}

/* 功能面板 */
.function-panel {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
  height: 100%;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  padding: 16px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  backdrop-filter: blur(20px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow-y: auto;
}

.function-panel.collapsed {
  opacity: 0;
  transform: translateX(-100%);
  pointer-events: none;
}

.function-card, .session-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.function-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.function-btn {
  width: 100%;
  height: 64px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 12px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 2px solid transparent;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  position: relative;
  overflow: hidden;
  padding: 0 20px;
}

.function-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.function-btn:hover::before {
  left: 100%;
}

.function-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 35px rgba(102, 126, 234, 0.4);
  border-color: rgba(255, 255, 255, 0.3);
}

.function-btn.active {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  box-shadow: 0 12px 35px rgba(245, 87, 108, 0.5);
  transform: translateY(-2px);
}

/* 会话列表 */
.session-list {
  max-height: 350px; /* 适中的高度显示约6-8个会话 */
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: #c0c4cc transparent;
}

.session-list::-webkit-scrollbar {
  width: 6px;
}

.session-list::-webkit-scrollbar-track {
  background: transparent;
}

.session-list::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.session-list::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

.session-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  margin-bottom: 12px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  background: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(10px);
  position: relative;
  overflow: hidden;
}

.session-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(102, 126, 234, 0.1), transparent);
  transition: left 0.5s;
}

.session-item:hover::before {
  left: 100%;
}

.session-item:hover {
  background: rgba(255, 255, 255, 0.8);
  border-color: #667eea;
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.2);
}

.session-item.active {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
  border-color: #667eea;
  color: #667eea;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  border-left: 4px solid #667eea;
}

.session-info {
  flex: 1;
  min-width: 0;
}

.session-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.session-time {
  font-size: 12px;
  color: #909399;
}

.delete-btn {
  opacity: 0;
  transition: opacity 0.3s;
}

.session-item:hover .delete-btn {
  opacity: 1;
}

/* 内容列 */
.content-col {
  height: 100%;
  transition: all 0.3s ease;
}

/* 内容面板 */
.content-panel {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  backdrop-filter: blur(20px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}
</style>
